package io.kiki.sba.registry.server.metadata.remoting.handler;

import io.kiki.sba.registry.api.Channel;
import io.kiki.sba.registry.common.model.ServerData;
import io.kiki.sba.registry.common.model.console.PersistenceData;
import io.kiki.sba.registry.common.model.metaserver.FetchProvideDataRequest;
import io.kiki.sba.registry.common.model.metaserver.ProvideData;
import io.kiki.sba.registry.server.metadata.provide.data.ProvideDataService;
import io.kiki.sba.registry.store.api.DBResponse;
import io.kiki.sba.registry.store.api.OperationStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * Handle session node's query request, such as get ProvideData by dataInfoId
 */
public class FetchProvideDataRequestHandler extends BaseMetaServerHandler<FetchProvideDataRequest> {

    private static final Logger logger = LoggerFactory.getLogger(FetchProvideDataRequestHandler.class);

    @Autowired
    private ProvideDataService provideDataService;

    @Override
    public Object doHandle(Channel channel, FetchProvideDataRequest fetchProvideDataRequest) {
        try {
            DBResponse<PersistenceData> persistenceDataDBResponse = provideDataService.queryProvideData(fetchProvideDataRequest.getDataInfoId());

            if (persistenceDataDBResponse.getOperationStatus() == OperationStatus.success) {
                PersistenceData persistenceData = persistenceDataDBResponse.getEntity();
                ProvideData provideData = new ProvideData(new ServerData(persistenceData.getData()), fetchProvideDataRequest.getDataInfoId(), persistenceData.getVersion());
                logger.info("get ProvideData {} from DB success!", provideData);
                return provideData;
            } else
                if (persistenceDataDBResponse.getOperationStatus() == OperationStatus.notfound) {
                    ProvideData provideData = new ProvideData(null, fetchProvideDataRequest.getDataInfoId(), null);
                    logger.warn("has not found data from DB dataInfoId:{}", fetchProvideDataRequest.getDataInfoId());
                    return provideData;
                } else {
                    logger.error("get Data DB status error!");
                    throw new RuntimeException("Get Data DB status error!");
                }

        } catch (Exception e) {
            logger.error("get persistence Data dataInfoId {} from db error!", fetchProvideDataRequest.getDataInfoId());
            throw new RuntimeException("Get persistence Data from db error!", e);
        }
    }

    @Override
    public Class interest() {
        return FetchProvideDataRequest.class;
    }
}
